package org.apache.zookeeper.recipes;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.concurrent.*;

/**
 * <h2></h2>
 * description:
 *
 * @author yongjun.ji(yongjun.ji @ ucarinc.com)
 * @since 1.0 2020/6/15 14:41
 */
public class DistributedLockDemo {
    public static void main(String[] args) throws Exception {
        CuratorFramework client = CuratorClient.getClient();
        client.start();
        System.out.println("连接成功");

        String lockPath = "/testLock";
        Runnable task = () -> {
            InterProcessMutex lock = new InterProcessMutex(client, lockPath);
            try {
                if (lock.acquire(1000L, TimeUnit.MILLISECONDS)) {
                    try {
                        // do some work inside of the critical section here
                        System.out.println(Thread.currentThread().getName() + " get the lock");
                        Thread.sleep(1000);
                    } finally {
                        lock.release();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        System.out.println("提交任务");
        ExecutorService executors = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            executors.submit(task);
        }
        System.out.println("提交完成");
        System.in.read();
        executors.shutdown();
    }

}
